import {defineStore} from "pinia";
import {reqGetCode, reqLogin} from "@/api/hospital";
import type {LoginData, LoginResponseData, UserInfo} from "@/api/hospital/type";
import type {userState} from "./interface";


const useUserStore = defineStore("user", {
	state: (): userState => {
		return{
			visible: false,  // 控制登录页面的显示和隐藏
			code:'',   // 验证码
			// 用户信息，包括token
			info: JSON.parse(localStorage.getItem("USERINFO") as string) || ({} as UserInfo),   // 存储用户账号
		}
	},
	actions: {
		// 获取验证码
		async getCode(phone: string) {
			const result:any = await reqGetCode(phone);
			if (result.code === 200) {
				this.code = result.data;
				return 'ok';
			}else{
				return Promise.reject(new Error(result.message))
			}
		},
		async userLogin(data: LoginData) {
			let result:LoginResponseData = await reqLogin(data)
			if (result.code === 200){
				this.info = result.data;
				// 将用户信息保存到本地储存中
				localStorage.setItem("USERINFO", JSON.stringify(this.info))
				return 'ok';
			}else{
				return Promise.reject(new Error(result.message))
			}
		},
		// 退出登录
		logout() {
			this.info = {} as UserInfo;
			localStorage.removeItem("USERINFO");
		},
		// 查询微信扫码结果
		queryState() {
			// 开启定时器，查看本地是否有用户信息
			let timer = setInterval(() => {
				if (localStorage.getItem("USERINFO")) {
					this.visible = false;
					this.info = JSON.parse(localStorage.getItem("USERINFO") as string);
					console.log(this.info);
					clearInterval(timer);
				}
			}, 1000)
		}
	},
	getters: {}
});

export default useUserStore;